package co.bugu.code.analysis.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * shell脚本工具
 * <p>
 * shell使用git-bash命令处理
 * bat使用windows自带cmd命令处理
 * <p>
 * 根据实际使用平台，优先使用对应的脚本。 除非在windows上执行shell命令，才使用bash
 *
 * @author daocers
 * @date 2025/3/29 18:52
 */
@Slf4j
public class ShellUtil {

    /**
     * 执行shell命令
     *
     * @param cmd shell命令，注意使用bash执行时候， cmd不能使用split("\\s+")切分为数组， 这点和bat脚本不同，但是原因尚未清楚
     * @return
     * @author alei
     * @date 2025/3/29 18:53
     */
    public static String executeShell(String workDir, String cmd) {
        try {
            if (StringUtils.isBlank(cmd)) {
                return "warning:空指令";
            }
            ProcessBuilder builder = new ProcessBuilder("D:\\program_files\\Git\\bin\\bash.exe", "-c", cmd);
            builder.redirectErrorStream(true);

            File file = new File(workDir);
            if (!file.exists()) {
                file.mkdirs();
//                throw new RuntimeException("工作目录不存在");
            }
            builder.directory(file);
            Process process = builder.start();

            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append("\t");
            }
            int exitCode = process.waitFor();

            if (exitCode == 0) {
                log.info("命令[{}]执行完毕: {}", cmd, buffer.toString());
            } else {
                log.error("命令[{}]执行失败: {}", cmd, buffer.toString());
            }
            return buffer.toString();
        } catch (Exception e) {
            log.error("执行命令[{}]异常", cmd, e);
        }
        return "";
    }


    public static String executeBat(String workDir, String cmd) {
        try {
            if (StringUtils.isBlank(cmd)) {
                return "warning:空指令";
            }
            cmd = "cmd.exe /c;  " + cmd;

            ProcessBuilder builder = new ProcessBuilder(cmd.split("\\s+"));
            builder.redirectErrorStream(true);
            File file = new File(workDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            builder.directory(file);
            Process process = builder.start();

            

            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line).append("\t");
            }
            boolean res = process.waitFor(1, TimeUnit.MINUTES);
            if(res){
                log.debug("命令[{} {}]执行完毕: {}", workDir, cmd, buffer.toString());
            } else {
                log.error("命令[{} {}]执行失败: {}",workDir, cmd,  buffer.toString());
            }
            return buffer.toString();
        } catch (Exception e) {
            log.error("执行命令[{}]异常", cmd, e);
        }
        return "";
    }
}
